<template>
  <div class="app-container">
    <!--选择仓库-->
    <SelectWarehouse ref="openSelectWarehouse"  @warehouseSelected="warehouseSelected"></SelectWarehouse>
    <SelectCustomer ref="openSelectCustomer"  @customerSelected="customerSelected"></SelectCustomer>
    <SelectPosition ref="openSelectPosition"  @positionSelected="positionSelected"></SelectPosition>
     <!-- 货物调仓/增加库内调仓 -->
     <div class="detail-title-box">
      <span>详情信息</span>
    </div>
      <el-form ref="ruleForm" :model="ruleForm" label-width="120px" :inline="true" :rules="rules" :label-position="labelPosition">
        <el-form-item label="客户" prop="khmc" :rules="rules.khmc">
          <el-input
              v-model="ruleForm.khmc"
              :disabled="true"
              style="width:225px"
          >
            <el-button slot="append" @click="customerSelect">选择</el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="库存" prop="spckmc" :rules="rules.spckmc">
          <el-input
              v-model="ruleForm.spckmc"
              :disabled="true"
          />
        </el-form-item>
        <el-form-item label="仓位" prop="ckcw" :rules="rules.ckcw">
          <el-input
              v-model="ruleForm.ckcw"
              :disabled="true"
              style="width:225px"
          >
            <el-button slot="append" @click="warehousePositionSelect">选择</el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="调仓类型" prop="dzrb">
           <el-select
            v-model="ruleForm.dzrb"
            placeholder="请选择调仓类型"
            clearable
            style="width: 240px"
          >
            <el-option
                v-for="(item, index) in MoveType"
                :key="index"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="dzbz">
          <el-input
            v-model="ruleForm.dzbz"
            placeholder="请输入备注"
            clearable
          />
        </el-form-item>
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
            <el-button type="primary" plain size="mini" @click="warehouseSelect">选择库存</el-button>
            </el-col>
        </el-row>
        <el-table
          :data="ruleForm.inp"
          class="form-table"
        >
          <af-table-column prop="khmc" label="客户" width="250"></af-table-column>
          <af-table-column prop="spzs" label="物品规格" width="150"></af-table-column>
          <af-table-column prop="spbh" label="批号" width="150"></af-table-column>
          <af-table-column prop="spgh" label="柜号" width="150"></af-table-column>
          <af-table-column prop="spckmc" label="原仓库" width="150"></af-table-column>
          <af-table-column prop="ckcw" label="原仓位" width="150"></af-table-column>
          <af-table-column prop="spcwid2" label="选择新仓位" width="150" :render-header="addRedStar">
            <template slot-scope="scope">
              <el-form-item :prop="'inp.' + scope.$index + '.spcwid2'" :rules="rules.inp.spcwid2">
                <el-select 
                  v-model="scope.row.spcwid2" 
                  placeholder="请选择" 
                  filterable
                  :loading="selectPosition1Loading"
                  size="mini"
                >
                  <el-option
                    v-for="item in warehouseSelectPositonList"
                    :key="item.liid"
                    :label="item.ckcw"
                    :value="item.liid">
                  </el-option>
                </el-select>
              </el-form-item>
            </template>
          </af-table-column>
          <af-table-column prop="spjs" label="转移件数" width="150" :render-header="addRedStar">
             <template slot-scope="scope">
              <el-form-item :prop="'inp.' + scope.$index + '.spjs'" :rules="rules.inp.spjs">
               <el-input v-model="scope.row.spjs" size="mini" placeholder="请输入内容" @input="getWeight(scope.$index)" type="number"/>
              </el-form-item>
            </template>
          </af-table-column>
          <af-table-column prop="spjs2" label="原库存件数" width="150"></af-table-column>
          <af-table-column prop="spjsl" label="单重(KG)" width="150"></af-table-column>
          <af-table-column prop="spsl" label="转移重量(吨)" width="150"></af-table-column>
          <af-table-column prop="ssrqidn" label="入仓日期" width="170"></af-table-column>
          <af-table-column prop="ssrqid" label="调仓日期" width="170"></af-table-column>
          <af-table-column prop="days" label="天数" width="150"></af-table-column>
        </el-table>
        <el-row class="mt20" :gutter="20">
          <el-form-item label="件数">{{ amountTotal }}</el-form-item>
          <el-form-item label="重量(吨)">{{ weightTotal }}</el-form-item>
        </el-row>
      </el-form>
      <el-row type="flex" justify="center" :gutter="5" class="mt20">
        <el-col :span="1.5">
          <el-button @click="goBack">返回</el-button>
        </el-col>
        <el-col :span="1.5">
            <el-button type="primary" @click="warehouseMoveSubmit('ruleForm')" v-hasPermi="['zhcloud:hwtc:add']">调仓</el-button>
        </el-col>
      </el-row>
  </div>
 
</template>

<script>
import { warehouseMoveAdd, selectPosition1 } from "@/api/storage/commonGoods/warehouseMove";
import SelectCustomer from './selectCustomer.vue';
import SelectWarehouse from './selectWarehouse.vue'
import SelectPosition from './selectPosition.vue'
import { WEIGHT_DIGIT, NUMBER_DIDGIT } from '@/utils/constant'

export default {
  name: "WarehouseInnerMove",
  components: { SelectCustomer, SelectWarehouse, SelectPosition },
  data() {
    return {
      // 显示搜索条件
      showSearch: true,
      // 对齐方式
      labelPosition:"right",
      //仓库加载
      selectPosition1Loading: true,
      //配送方式
      MoveType:[
        {label:"客户调仓", value:"ck_spdj16"},
        {label:"内部调仓", value:"ck_spdj15"},
      ],
      //选择明细仓位参数
      selectPositonQuery:{
        spckid:""
      },
      //添加详情
      ruleForm:{
        isBa: "",
        khlx: "商城",
        khmc: "",
        khmcid: "",
        khpb: 0,
        shopId: 0,
        spckidis: [],
        spckidn: "",
        spcwidn: "",
        dzbz: "",
	      dzrb: "ck_spdj16",
        ckcw: "",
        liid:"",
        spckmc:"",
        inp:[]
      },
      //校验
      rules: {
        khmc:[{
          required: true,
          message: '客户不能为空',
          trigger: "blur"
        }],
        spckmc:[{
          required: true,
          message: '库存不能为空',
          trigger: "blur"
        }],
        inp:{
          spcwid2: [
            {
              required: true,
              message: '仓位不能为空',
              trigger: "blur"
            }
          ],
          spjs: [
            {
              required: true,
              message: '转移件数不能为空',
              trigger: "blur"
            },
            {
              required: true,
              validator: this.checkspsl,
              trigger: "blur"
            }
          ],
        }
      },
      amountTotal:0,
      weightTotal:0,
      //选择明细仓位列表
      warehouseSelectPositonList:[],
      //选择客户和仓库数据
      selectCustomerData:{},
    };
  },
  watch: {
    'ruleForm.inp': {
      handler:function (newData, oldData) {
        let spjsSum = 0
        let spslSum = 0
        for(let i in newData) {
          if(newData[i].spjs) {
            spjsSum += parseFloat(newData[i].spjs)
          }
          if(newData[i].spsl) {
            spslSum += parseFloat(newData[i].spsl)
          }
        } 
        this.amountTotal = parseFloat(spjsSum.toFixed(NUMBER_DIDGIT))    
        this.weightTotal = parseFloat(spslSum.toFixed(WEIGHT_DIGIT))   
      },
      deep:true
    },
  },
  methods: {
    /**选择新仓位列表 */
    positionSelect() {
      this.selectPosition1Loading = true
      selectPosition1(this.selectPositonQuery).then(response => {
        this.warehouseSelectPositonList = response.data
        this.selectPosition1Loading = false
      });
    },
    /**调仓 */
    warehouseMoveSubmit(formName) {
      this.$refs[formName].validate((valid, data) => {
        if(valid) {
          if(this.ruleForm.inp.length > 100) return this.$modal.msgError("货物行数不能大于100行！")
          if(this.ruleForm.inp.length === 0) return this.$modal.msgError("请先输入数据！")
          this.$modal.loading("数据正在执行中，请稍等...")
          warehouseMoveAdd(this.ruleForm).then(response => {
            this.$modal.closeLoading()
            this.$modal.msgSuccess('执行成功')
            this.goWarehouseMove()
          }).catch(()=> {
            this.$modal.closeLoading()
          })
        } else {
          for(let i in data) {
            const item = data[i]
            for(let j in item) {
              const message = item[j].message
              return this.$modal.msgError(message)
            }
          }
          return false
        }
      })
    },
    /** 添加行删除*/
    handleRowDelete(index) {
      this.ruleForm.inp.splice(index, 1)
    },
    /**选择客户 */
    customerSelect() {
      this.$refs.openSelectCustomer.open()
    },
    /**选择仓库 */
    warehouseSelect() {
      if(!this.ruleForm.khmc) return this.$modal.msgError("请先选择客户！")
      const inp = this.ruleForm.inp
      this.$refs.openSelectWarehouse.open(inp, this.selectCustomerData)
    },
    /**选择仓位 */
    warehousePositionSelect() {
        if(!this.ruleForm.khmc) return this.$modal.msgError("请先选择客户！")
        this.$refs.openSelectPosition.open(this.selectCustomerData)
    },
    /**选择仓库返回 */
    warehouseSelected(data) {
      if(data) {
        for(let i in data) {
          data[i].khmc = data[i].spkhmc
          data[i].itbz = this.ruleForm.dzbz
          this.$set(data[i], "spcwid2", this.ruleForm.liid)
          this.ruleForm.inp.push(data[i])
        }
      }
    },
    /**选择用户返回 */
    customerSelected(data) {
      this.selectCustomerData = data
      const {isBa="",khlx= "",khmc= "",khid:khmcid,khpb= 0,shopId= 0,spckidis= [],spckid:spckidn,spcwidn= "",dzbz= "",dzrb= "ck_spdj16",ckcw= "",spckmc="",inp=[]} = data
      this.ruleForm = {...this.ruleForm,isBa,khlx,khmc,khmcid,khpb,shopId,spckidis,spckidn,spcwidn,dzbz,dzrb,ckcw,spckmc,inp}
      this.selectPositonQuery.spckid = data.spckid
      this.positionSelect()
    },
    /**选择仓位返回 */
    positionSelected(data) {
        this.ruleForm.ckcw = data.ckcw
        this.ruleForm.liid = data.liid
        this.ruleForm.inp = []
    },
    /**验证转移件数 */
    checkspsl(rule, value, callback) {
      const a = rule.field.split('.')
      const index = a[1]
      const spjs2 = parseFloat(this.ruleForm.inp[index].spjs2)
      if(spjs2 < value) {
        callback("转移件数不可超过原库存件数")
      } else {
        callback()
      }
    },
    /**计算重量 */
    getWeight(index) {
      const r = this.ruleForm.inp[index]
      let spjs = r.spjs
      if(spjs.indexOf('.')>0){
        spjs=spjs.slice(0,spjs.indexOf('.')+4)
      }
      r.spjs = spjs
      r.spsl = parseFloat((spjs*r.spjsl/1000).toFixed(WEIGHT_DIGIT))
    },
    //跳回货物入仓页
    goWarehouseMove() {
      this.$tab.closePage(this.$route)
      this.$router.push({name:"WarehouseMove", params:{refresh:true}})
    },
    // 给表头加必填符号*
    addRedStar(h, { column }) {
      return [
        h("span", { style: "color: red" }, "*"),
        h("span", " " + column.label),
      ];
    },
    reset(vm) {
      Object.assign(vm.$data, vm.$options.data())
    },
      /**返回不刷新 */
    goBack() {
      this.$router.push({name:"WarehouseMove"})
    }
  }
};
</script>
